import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wkweb/layout/list_page.dart';
import 'package:wkweb/layout/nav_page.dart';
import 'package:wkweb/layout/web_page.dart';
import 'package:wkweb/models/allmodels.dart';
import 'package:wkweb/res/wk_theme.dart';
import 'package:wkweb/util/route_paths.dart';
import 'package:wkweb/util/utils.dart';
import 'package:wkweb/view/wk_loading_header.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => GlobalModel()),
        ChangeNotifierProvider(create: (_) => TabModel()),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return RefreshConfiguration(
        //下拉刷新全局配置
        headerBuilder: () => wkLoadHeader(),
        footerBuilder: () => ClassicFooter(),
        child: MaterialApp(
          title: 'Wk',
          theme: globalTheme(),
          darkTheme: globalDarkTheme(),
          routes: _routes(),
          home: SafeArea(child: MyHomePage(title: 'WkAndroid')),
        ));
  }

  _routes() {
    return {RoutePaths.pathWebPage: (context) => WebPage()};
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<BottomNavigationBarItem> navItems = [
    BottomNavigationBarItem(icon: Icon(Icons.list), label: "文章"),
    BottomNavigationBarItem(icon: Icon(Icons.navigation), label: "导航"),
  ];

  var _lastPressedAt;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_lastPressedAt == null ||
            DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 1)) {
          //两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          Utils.showTextSnack(context, "再次返回退出程序");
          return false;
        }
        return true;
      },
      child: Container(
          alignment: Alignment.center,
          child: Scaffold(
              body: IndexedStack(
                index: context.watch<TabModel>().currentIndex,
                children: [ListPage(), NavPage()],
              ),
              bottomNavigationBar: BottomNavigationBar(
                items: navItems,
                onTap: (int index) {
                  context.read<TabModel>().setCurrent(index);
                },
                currentIndex: context.watch<TabModel>().currentIndex,
              ))),
    );
  }
}
